package com.example.suze.libraryinformationmanagementsystem.net;

import android.support.v7.app.AppCompatActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Objects;

/**
 * Created by Luo on 2017/6/17.
 *
 */

public class API {

    //private static String url = "http://localhost:8080/LibraryManagementService/Servlet";  //本地服务器（虚拟机无法访问Windows IP）
//    private static String url = "http://10.0.2.2:8080/LibraryManagementService/Servlet";     //10.0.2.2为本机在虚拟机上的映射IP
    private static String url = "http://192.168.31.8:8080/LibraryManagementService/Servlet"; //腾讯云
    private JSONRequest request = new JSONRequest();
    private JSONObject json = new JSONObject();
    private static API api = null;                        //单例模式

    private API(){}

    public static API getAPI(AppCompatActivity activity){
        synchronized (activity){
            if(api == null){
                api = new API();
            }
            return api;
        }
    }

    public void login(String username, String password, JSONCallBack callBack){
        try {
            json.put("type", "login");
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("username", username);
            jsonObj.put("password", password);
            json.put("data", jsonObj);
            request.request(url, json, callBack);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void sqlOporate(String opt, String sql, JSONCallBack callBack){
        try {
            json.put("type", "sql");
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("opt", opt);
            jsonObj.put("sql", sql);
            json.put("data", jsonObj);
            request.request(url, json, callBack);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    public void borrowInfo(String opt, String sql, JSONCallBack callBack){
        try {
            json.put("type", "info");
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("opt", opt);
            jsonObj.put("sql", sql);
            json.put("data", jsonObj);
            request.request(url, json, callBack);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
